/*******************************************************************************
 * Copyright (c) 2011 Irineu Martins de Lima Moura (imlm2).
 * This file is part of JBeat.
 * 
 *     JBeat is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     JBeat is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with JBeat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Irineu Martins de Lima Moura (imlm2) - initial API and implementation
 ******************************************************************************/
package br.ufpe.cin.imlm2.jbeat.soot.throwableset;

import java.util.*;

import soot.SootClass;
import soot.SootMethod;
import soot.jimple.toolkits.scalar.UnreachableCodeEliminator;

import br.ufpe.cin.imlm2.jbeat.soot.common.MethodTagger;

public abstract class InstructionInspector extends MethodTagger {

	protected abstract void visitInstructions(SootMethod sootMethod);

	protected void filterOutMethods(Iterable<SootMethod> it) {
		Iterator<SootMethod> meths = it.iterator();
		while (meths.hasNext()) {
			SootMethod sootMethod = meths.next();
			if (!sootMethod.isConcrete()) {
				meths.remove();
			}
		}
	}

	@Override
	protected void executePreTaggingTransformations(
			Collection<SootClass> classes) {
		super.executePreTaggingTransformations(classes);
		UnreachableCodeEliminator uce = UnreachableCodeEliminator.v();
		for (SootClass sootClass : classes) {
			for (SootMethod sootMethod : sootClass.getMethods()) {
				if (sootMethod.isConcrete())
					uce.transform(sootMethod.retrieveActiveBody());
			}
		}
	}

	@Override
	protected void tag(Collection<SootClass> classes) {
		System.err.println("Instruction inspection beggining at "
				+ Calendar.getInstance().getTime());
		Long startTime = System.currentTimeMillis();
		for (SootClass sootClass : classes) {
			List<SootMethod> allMethods = new ArrayList<SootMethod>(
					sootClass.getMethods());
			this.filterOutMethods(allMethods);
			for (SootMethod sootMethod : allMethods) {
				this.visitInstructions(sootMethod);
			}

		}
		System.err.println("Instruction inspection finished in "
				+ (System.currentTimeMillis() - startTime) + "ms at "
				+ Calendar.getInstance().getTime());

	}
}
